//  this library.
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_inapp_purchase/flutter_inapp_purchase.dart';
import 'package:hktk_app/dao/package_dao.dart';
import 'package:hktk_app/ienum/package/payment_type_enum.dart';

// 暂时只设置了这一个内购项目
final Map<int, String> _productMap = {
  38: "zzwxtc038",
  68: "zzwxtc068",
  98: "zzwxtc098",
  128: "zzwxtc128",
  168: "zzwxtc168",
  198: "zzwxtc198",
  1548: "zzwxtc1548",
};

/// iOS应用内购买工具类
class BuyIOSUtil {
  /// 根据实际价格获取苹果阶梯价格
  static double getIosPrice(double price) {
    if (price >= 1548) {
      return 1548;
    } else if (price >= 198) {
      return 198;
    } else if (price >= 168) {
      return 168;
    } else if (price >= 128) {
      return 128;
    } else if (price >= 98) {
      return 98;
    } else if (price >= 68) {
      return 68;
    } else {
      return 38;
    }
  }

  /// 判断购买是否完成
  bool _isPaying = false;

  /// 关闭iOS支付链接
  void closeIosConnection() async {
    await FlutterInappPurchase.instance.finalize();
  }

  /// 销毁之前的订单，否则无法多次购买
  Future<String?> clearTransaction() async {
    return FlutterInappPurchase.instance.clearTransactionIOS();
  }

  /// iOS开始购买
  void doIOSPay({
    required double iosPrice,
    required String orderId,
    required VoidCallback onConnectAppStore,
    required VoidCallback onSuccess,
    required Function(String error) onError,
  }) async {
    if (_isPaying) return;
    _isPaying = true;

    // 创建对应的支付信息
    await PackageDao.paySign(
      type: PaymentTypeEnum.applypay,
      orderId: orderId,
    );

    /// 获取对应的产品id
    String productId = _productMap[iosPrice] ?? "";

    List<IAPItem> products =
    await FlutterInappPurchase.instance.getProducts([productId]);
    String s1 = jsonEncode(products);
    if (products.isEmpty) {
      _isPaying = false;
      onError.call("没有找到相关产品");
      return;
    }

    // debugPrint("初始化连接开始 ===> ");
    String? initStr = await FlutterInappPurchase.instance.initialize();
    // debugPrint("初始化连接结束 ===> $initStr");
    //
    // debugPrint("连接状态开始监听 ===> ");
    FlutterInappPurchase.connectionUpdated.listen((connected) {
      /// 调起苹果支付，这时候可以关闭toast
      onConnectAppStore.call();
    });

    FlutterInappPurchase.purchaseUpdated.listen((producItem) async {
      if (producItem != null) {
        // 验证收据，这里直接校验，是否成功
        // Map<String, String> iosMap = {
        //   "receipt-data": producItem.transactionReceipt ?? "",
        // };
        // try {
        //   debugPrint("验证收据 ===> ");
        //   Response response = await FlutterInappPurchase.instance
        //       .validateReceiptIos(
        //     receiptBody: iosMap,
        //     isTest: false,
        //   );
        //   var decodeMap = jsonDecodeMap(response);
        //   debugPrint("iOS验证收据返回值 ===> $decodeMap");
        //   // if (decodeMap["status"] == 0) {
        //   //
        //   // }
        // } catch(e) {
        //   debugPrint("iOS验证收据时发生异常 ===> $e");
        // }

        String? s2 = await clearTransaction();

        /// 购买成功回调
        onSuccess.call();
      }
      _isPaying = false;
    });

    FlutterInappPurchase.purchaseError.listen((purchaseError) async {
      if (purchaseError != null) {
        _isPaying = false;

        String? s2 = await clearTransaction();

        await FlutterInappPurchase.instance.finalize();

        // 判断是否是取消支付
        if (purchaseError.code == "E_USER_CANCELLED") {
          // 取消支付
          onError.call("支付已取消");
        } else {
          /// 购买错误回调
          onError.call("购买失败");
        }
      }
    });

    // obfuscatedAccountId: "" ，https://github.com/hyochan/flutter_inapp_purchase/issues/495
    FlutterInappPurchase.instance.requestPurchase(productId, obfuscatedAccountId: "");
  }
}
